#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
using namespace std;

int main()
{
    const char *filename = "./testFifo";
    /* 判断管道文件是否存在 */
    int ret = access(filename, F_OK);
    if (ret != 0)
    {
        /* 文件不存在才需要创建 */
        ret = mkfifo(filename, 0644);
        if (ret == -1)
        {
            perror("mkfifo error");
            exit(-1);
        }
    }

    /* 创建子进程 */
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid == 0)
    {
        cout << "l am child process." << endl;

        /*1.打开文件*/
        int fd = open(filename, O_RDWR);
        if (fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }
        /*2.读取数据*/
        int readBytes = 0;
        char buffer[11] = {0};
        while (1)
        {
            readBytes = read(fd, buffer, sizeof(buffer));
            if (readBytes < 0)
            {
                perror("read perror:");
                _exit(-1);
            }
            cout << "readBytes:" << readBytes << ", buffer:" << buffer << endl;
        }

        /*3.关闭文件*/
        close(fd);
    }
    else
    {
        cout << "l am parent process." << endl;
        /* 1.打开文件*/
        int fd = open(filename, O_RDWR);
        if (fd == -1)
        {
            perror("open error:");
            _exit(-1);
        }
        /* 2.向文件中写数据：helloworld */
        const char *data = "helloworld";
        int writeBytes = 0;
        while (1)
        {
            writeBytes = write(fd, (const void *)data, strlen(data));
            cout << "writeBytes:" << writeBytes << endl;
            /* 休眠1s */
            sleep(1);
        }
        /* 3.关闭文件 */
        close(fd);
    }

    while (1)
    {
        sleep(1);
    }

    return 0;
}
